package cn.com.visionsky.bocsz.bda.webservice.ws;

import cn.com.visionsky.bocsz.bda.webservice.exception.RequestXmlException;
import cn.com.visionsky.bocsz.bda.webservice.exception.ResponseXmlException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * Created by 46043 on 2016/11/11.
 */
public class FullTextUtils {
    private static final Logger logger = LoggerFactory
            .getLogger(FullTextUtils.class);

    public static <T> T getFullTextRequest(Class<T> c, String fullTextRequestStr) {
        try {
            return (T)JAXBContext.newInstance(c).createUnmarshaller().unmarshal(new StreamSource(new StringReader(fullTextRequestStr)));
        } catch (JAXBException e) {
            logger.error("reqest xml exception!", e);
            throw new RequestXmlException("reqest xml exception!");
        }
    }

    public static String getFullTextResponseStr(Object obj) {
        try {
            Marshaller marshaller = JAXBContext.newInstance(obj.getClass()).createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// //编码格式
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 是否格式化生成的xml串
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);// 是否省略xm头声明信息
            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            return writer.toString();
        } catch (JAXBException e) {
            logger.error("response xml exception!", e);
            throw new ResponseXmlException("response xml exception!");
        }

    }
}
